<?php

namespace core;

use core\Config;
use core\db\Mysql;

class Db
{
    public static $instance;

    private static $dbCon;

    public static $cfg;

    private $tname;

    private $fields = '';

    private $alias;

    private $condition;

    private $join;

    private $order;

    private $limitStart;
    private $limitEnd;

    private function __construct()
    {
        // 装载配置文件
        $config = new Config();
        self::$cfg = $config->getConfig();

        if (strtolower(self::$cfg['db_type']) == 'mysql') {
            $mysqlCon = new Mysql(self::$cfg['db_host'], self::$cfg['db_user'], self::$cfg['db_passwd'], self::$cfg['db_name']);
            self::$dbCon = $mysqlCon->getConnection();
        }
    }

    private function __clone()
    {
    }

    public static function getInstance()
    {
        if (self::$instance instanceof self) {
            return self::$instance;
        } else {
            self::$instance = new Db();
            return self::$instance;
        }
    }

    public function table($tableName)
    {
        $this->tname = $tableName;
        return $this;
    }

    public function field($fields)
    {
        if (is_array($fields)) {
            $this->fields = implode(',', $fields);
        } else {
            $this->fields = $fields;
        }
        return $this;
    }

    public function alias($alias)
    {
        $this->alias = $alias;
        return $this;
    }

    public function where($condition)
    {
        if (is_array($condition)) {
            $this->condition = implode(' AND ', $condition);
        } else {
            $this->condition = ' ' . $condition . ' ';
        }
        return $this;
    }

    public function join($join)
    {
        $this->join = $join;
        return $this;
    }

    public function limit($start, $end = 0)
    {
        $this->limitStart = $start;
        $this->limitEnd = $end;
        return $this;
    }

    public function order($order)
    {
        if (is_array($order)) {
            $this->order = implode(',', $order);
        } else {
            $this->order = $order;
        }
        return $this;
    }

    /**
     * 查询所有记录
     */
    public function findAll()
    {
        $sql = $this->querySqlConcat('all');
        $queryRes = $this->sqlQuery($sql);
        return $this->formatQueryRes($queryRes);
    }

    /**
     * 查询记录
     */
    public function find()
    {
        $sql = $this->querySqlConcat('common');
        $queryRes = $this->sqlQuery($sql);
        return $this->formatQueryRes($queryRes);
    }

    /**
     * 查询单条记录
     */
    public function findOne()
    {
        $sql = $this->querySqlConcat('one');
        // return $sql;
        $queryRes = $this->sqlQuery($sql);
        return $this->formatQueryRes($queryRes);
    }

    /**
     * 拼接 query sql
     */
    public function querySqlConcat($numLimit)
    {
        if ($this->tname == '') {
            return '请指定要查询的数据表名称！';
        }

        if ($this->fields != '') {
            $sql = 'SELECT ' . $this->fields . ' ';
        } else {
            $sql = 'SELECT * ';
        }
        $sql .= ' FROM ' . $this->tname . ' ';

        if ($this->alias != '') {
            $sql .= ' ALIAS ' . $this->alias . ' ';
        }

        if ($this->condition != '') {
            $sql .= ' WHERE ' . $this->condition . ' ';
        } else {
            $sql .= ' WHERE 1=1 ' . ' ';
        }

        if ($this->order != '') {
            $sql .= ' ORDER BY ' . $this->order . ' ';
        }

        switch ($numLimit) {
            case 'all':
                break;
            case 'one':
                $sql .= ' LIMIT 1 ';
                break;
            default:
                if ($this->limitStart && $this->limitEnd) {
                    $sql .= ' LIMIT ' . $this->limitStart . ',' . $this->limitEnd . ' ';
                } elseif ($this->limitStart) {
                    $sql .= ' LIMIT ' . $this->limitStart . ' ';
                }
                break;
        }

        return $sql;
    }

    /**
     * 运行 query sql
     */
    private function sqlQuery($sql)
    {
        return mysqli_query(self::$dbCon, $sql);
    }

    /**
     * 格式化查询结果
     */
    private function formatQueryRes($queryRes)
    {
        return $queryRes->fetch_all(MYSQLI_ASSOC);
    }
}
